package com.hctforgreen.greenservice;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import u.aly.cb;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import cn.dns.reader.network.BookDownloaderService;
import cn.dns.reader.network.BookDownloaderServiceConnection;

import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctBackTestJsonController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BaseEntity;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.DataVersionCodeEntity;
import com.hctforgreen.greenservice.model.SerieListEntity;
import com.hctforgreen.greenservice.model.SeriesForNodeEntity;
import com.hctforgreen.greenservice.service.HctApplication;
import com.hctforgreen.greenservice.service.TechnicalDataUpdateService;
import com.hctforgreen.greenservice.threeLevelList.Node;
import com.hctforgreen.greenservice.threeLevelList.TreeHelper;
import com.hctforgreen.greenservice.threeLevelList.TreeListViewAdapter;
import com.hctforgreen.greenservice.ui.adapter.AllBooksWithDbAllSeriesListAdapterV5;
import com.hctforgreen.greenservice.ui.adapter.DownloadManagerAdapter;
import com.hctforgreen.greenservice.ui.handler.AllBooksWithDbAllSeriesListHandlerV3;
import com.hctforgreen.greenservice.ui.page.AbstractDataResult;
import com.hctforgreen.greenservice.utils.DataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.EntryCataStoreUtil;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.GroupDialog;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.hctforgreen.greenservice.utils.VersionUtil;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

/**
 * 下载管理页
 *
 * @author Tallen Zhai
 *
 */
public class DownloadManagerActivityV2 extends ParentActivity implements TreeListViewAdapter.OnTreeNodeClickListener{

	//后台操作数据库的Service名
	private final String SERVICE_NAME = "com.hctforgreen.greenservice.service.TechnicalDataUpdateService";
	private DownloadUpdateReceiver mUpdateReceiver;

	//private AllBooksWithDbAllSeriesListAdapterV5 mAdapter;
	private AllBooksWithDbAllSeriesListAdapterV5 mAdapterDownLoad;// 已下载
	private DownloadManagerAdapter downloadManagerAdapter;
	private boolean fromMain;
	private boolean fromTerminalLearning;
	private boolean isNewVersion = true;

	private CheckBox cbDownloadList ;
	private CheckBox cbHasDownlaod ;

	private LinearLayout download_listView;
	private LinearLayout downloaded_ListView;
	private LinearLayout loadLyt;
	private LinearLayout reloadLyt;
	private LinearLayout emptyLyt;
	private ListView contentLyt;
	private Button reloadBtn;
	private TextView loadTv;

	private boolean mLoading;
	private int mMaxItems;
	private HctController mController = null;
	private Activity mActivity;
	/**
	 * 三级列表显示的数据list
	 */
	private List<SeriesForNodeEntity> threeLevelDataList = new ArrayList<SeriesForNodeEntity>();
	//大系列
	private List<SerieListEntity.SerieEntity> serieEntities = new ArrayList<SerieListEntity.SerieEntity>();
	//书
	private BookListEntity bookListEntityFromNet = new BookListEntity();
	private long mLExitTime = 0;
	private final long mLDelayTime = 2000;
	//资料包版本实体类
	DataVersionCodeEntity versionCodeEntity = null;

	GroupDialog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_download_manager_v2);
		this.mActivity = DownloadManagerActivityV2.this;
		mController = new HctController(this);

		findView();
		initRefreshBtn();
		fromMain = getIntent().getBooleanExtra("fromMain", false);
		fromTerminalLearning = getIntent().getBooleanExtra("fromTerminalLearning",false);

		initSkinLayout();
		initTitleButtonBar();//初始化切换页面
		initWindow();

		initDownloadUpdateReceiver();
		bindDownloadService();

	}
	/**
	 * //初始化下载管里title顶部刷新按钮
	 */
	private void initRefreshBtn() {
		Button refreshBtn = (Button) mActivity.findViewById(R.id.btn_right);
		refreshBtn.setBackgroundResource(R.drawable.update_all_books);
		refreshBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				//Toast.makeText(mActivity, "btntbtn", 0).show();
				View loadLyt = mActivity
						.findViewById(R.id.lyt_three_level_load);
				if (((DownloadManagerActivityV2) mActivity).getConnection()
						.hasDownloadingUrl()
						|| loadLyt.getVisibility() == View.VISIBLE) {
					LogUtil.i("DATA","有资料在下载 不能刷新  return");
					return;
				}

				//((DownloadManagerActivityV2) mActivity).refreshDataLst(type);
                /*
				 * 20160609
				 * 390694添加书籍资料版本检测
				 * 用于书籍刷新
				 */
				checkDataVersionCodeToRefres();
			}
		});
	}
	/**
	 * 用于每次进入页面时检测数据包版本是否需要更新
	 *
	 * @return
	 */
	public void checkDataVersionCodeToRefres() {

		final Handler handler = new Handler() {

			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
					case HctConstants.STATUS_SUCCESS:
						hctResult = (HctResult) msg.obj;

						DataVersionCodeEntity entity = (DataVersionCodeEntity) hctResult.data;

						String localVersionCode = DataVersionCodeUtil
								.getBookVersion(mActivity);

						LogUtil.i("DATA", "书-localVersionCode=" + localVersionCode);
						LogUtil.i("DATA", "书-entity.versionCode=" + entity.versionCode);
						if (!localVersionCode.equals(entity.versionCode)) {
							DataVersionCodeUtil
									.saveBookVersion(mActivity, entity.versionCode);
							//重新将更新资料的服务偏好设置初始化为false，防止边更新边下载时报错
							DownloadBookLstInitFinishUtil.saveDownloadBookFinished(mActivity,false);

							refreshDataLst(0, true);
							if (download_listView.getVisibility()==View.GONE){
								download_listView.setVisibility(View.VISIBLE);
							}
							if (!cbDownloadList.isChecked()) {
								cbDownloadList.setChecked(true);
							}
							cbHasDownlaod.setChecked(false);

							//390778增加进度条
							LogUtil.i("DATA", "启动新的dialog");

							HctApplication.percent = 5;
							GroupDialog dialog = new GroupDialog(DownloadManagerActivityV2.this);
							dialog.builder(R.style.AlertDialogStyle).
									setAlertDialogSize(0.05).setProgressBarRound(100).setCancleBack(DownloadManagerActivityV2.this).
									setCancleOnTouchOutside(false).show();

						} else {
							Dialog dialog = null;
							AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
							builder.setTitle(R.string.dialog_default_title_hint)
									.setMessage(R.string.download_manager_data_new)
									.setPositiveButton(R.string.dialog_confirm_hint, new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											dialog.dismiss();
										}
									});

							dialog = builder.create();
							dialog.show();

						}

						break;

					case HctConstants.STATUS_FAILD:

						Toast.makeText(mActivity,
								mActivity.getString(R.string.net_error_hint),
								Toast.LENGTH_SHORT).show();
						break;
				}


			}

		};

		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(DownloadManagerActivityV2.this);

					HctResult result = controller.getBookDataVersionCode();
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();

	}
	private void bindDownloadService() {
		final Intent intent = new Intent();
		intent.setClass(DownloadManagerActivityV2.this,
				BookDownloaderService.class);

		bindService(intent, connection, Activity.BIND_AUTO_CREATE);
	}

	// private void initSkinLayout() {
	// FrameLayout parentLyt = (FrameLayout) findViewById(R.id.lyt_parent);
	// parentLyt.setBackgroundResource(ThemeStoreUtil.getSkinId(this));
	// }

	private void initDownloadUpdateReceiver() {
		/**
		 * 注册下载进度条的监听,在BookShelfAdapter中实现
		 */
		mUpdateReceiver = new DownloadUpdateReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(HctConstants.RECEIVER_BOOKSHELF_ACTIVITY_DOWNLOAD_UPDATE);
		registerReceiver(mUpdateReceiver, filter);
	}

	private BookDownloaderServiceConnection connection = new BookDownloaderServiceConnection();

	public BookDownloaderServiceConnection getConnection() {
		return connection;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mUpdateReceiver);

		unbindService(connection);
	}

	private void initTitleButtonBar() {

		// final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		// titleTv.setText(getString(R.string.download_mannager_title_hint));
		final View convertView = findViewById(R.id.lyt_parent);
		download_listView = (LinearLayout) convertView.findViewById(R.id.lst_three_level_parent);
		downloaded_ListView = (LinearLayout) convertView.findViewById(R.id.lst_expandable_list_parent);
		cbDownloadList.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// if (cbDownloadList.isChecked()) {
				// return;
				// }

				if (download_listView.getVisibility() == View.GONE){
					download_listView.setVisibility(View.VISIBLE);
				}
				if (downloaded_ListView.getVisibility() == View.VISIBLE){
					downloaded_ListView.setVisibility(View.GONE);
				}
				//重新加载时，显示进度条
				loadLyt.setVisibility(View.VISIBLE);
				new getAllBooksTask(DownloadManagerActivityV2.this, false).execute();

				/*if (downloadManagerAdapter.getMList() == null
						|| downloadManagerAdapter.getMList().isEmpty()) {
					findViewById(R.id.lst_default_list)
							.setVisibility(View.GONE);
					findViewById(R.id.lyt_default_list_empty).setVisibility(
							View.VISIBLE);
				} else {
					findViewById(R.id.lst_default_list).setVisibility(
							View.VISIBLE);
					findViewById(R.id.lyt_default_list_empty).setVisibility(
							View.GONE);
				}*/
				cbHasDownlaod.setChecked(false);
				cbDownloadList.setChecked(true);
			}
		});
		cbHasDownlaod.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// if (cbHasDownlaod.isChecked()) {
				// return;
				// }
				if (download_listView.getVisibility() == View.VISIBLE){
					download_listView.setVisibility(View.GONE);
				}
				if (downloaded_ListView.getVisibility() == View.GONE){
					downloaded_ListView.setVisibility(View.VISIBLE);
				}
				//if (mAdapterDownLoad == null) {
					initDataLst(1,false);
				/*} else {
					View convertView = findViewById(R.id.lyt_parent);
					ExpandableListView listView = (ExpandableListView) convertView
							.findViewById(R.id.lst_default_list);
					listView.setAdapter(mAdapterDownLoad);
					mAdapterDownLoad.notifyDataSetChanged(1);
					if (mAdapterDownLoad.getmList() == null
							|| mAdapterDownLoad.getmList().isEmpty()) {
						findViewById(R.id.lst_default_list).setVisibility(
								View.GONE);
						findViewById(R.id.lyt_default_list_empty)
								.setVisibility(View.VISIBLE);
					} else {
						findViewById(R.id.lst_default_list).setVisibility(
								View.VISIBLE);
						findViewById(R.id.lyt_default_list_empty)
								.setVisibility(View.GONE);
					}

				}*/
				cbHasDownlaod.setChecked(true);
				cbDownloadList.setChecked(false);
			}
		});

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (fromMain) {
					startActivity(new Intent(DownloadManagerActivityV2.this,
							MainActivityV2.class));
					finish();
				} /*else if(fromTerminalLearning){
					Dialog dialog = null;
					AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
					builder.setTitle(R.string.dialog_default_title_hint)
							.setMessage(tipsId)
							.setPositiveButton(R.string.terminal_update_data_yes,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
															int which) {
											dialog.dismiss();
										}
									})
							.setNegativeButton(R.string.terminal_update_data_no,
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(DialogInterface dialog,
															int which) {
											dialog.dismiss();

										}
									});
					dialog = builder.create();
					dialog.show();

					finish();
				}*/ else {
					finish();
				}
			}
		});
	}

	/**
	 *
	 * @param type
	 * @param isRefresh 2016-12-15 390694 增加是否是点击了顶部的刷新按钮的判断参数
     */
	public void initDataLst(int type,boolean isRefresh) {
		// getAllSeriesFromDb();
		getAllBooksWithDbAllSeries(type,isRefresh);
	}
    //已下载列表刷新用
	public void freshAdapter() {
		if (mAdapterDownLoad != null) {
			View convertView = findViewById(R.id.lyt_parent);
			ExpandableListView listView = (ExpandableListView) convertView
					.findViewById(R.id.lst_default_list);
			listView.setAdapter(mAdapterDownLoad);
			if (mAdapterDownLoad.getmList() == null || mAdapterDownLoad.getmList().isEmpty()) {
				findViewById(R.id.lst_default_list).setVisibility(View.GONE);
				findViewById(R.id.lyt_default_list_empty).setVisibility(
						View.VISIBLE);
			} else {
				findViewById(R.id.lst_default_list).setVisibility(View.VISIBLE);
				findViewById(R.id.lyt_default_list_empty).setVisibility(
						View.GONE);
			}

			mAdapterDownLoad.notifyDataSetChanged();
		}
	}
	//首次安装或更新时刷新用
	public void freshAdapterFirstTime(final BookListEntity.BookEntity bookEntity) {
		 final Handler myHandler = new Handler(){

			 @Override
			 public void handleMessage(Message msg) {
				 super.handleMessage(msg);
				 //重新加载时，显示进度条
				 loadLyt.setVisibility(View.GONE);
				 switch (msg.what) {
					 case 1:
						 List<SeriesForNodeEntity> bookListEntity = (List<SeriesForNodeEntity>) msg.obj;
						 try {
							 boolean state = DownloadBookLstInitFinishUtil.getDownloadBookFinished(getApplication());
							 downloadManagerAdapter = new DownloadManagerAdapter<SeriesForNodeEntity>(contentLyt,
									 mActivity, bookListEntity, 1, 0,state);
							 contentLyt.setAdapter(downloadManagerAdapter);
							downloadManagerAdapter.setOnTreeNodeClickListener(DownloadManagerActivityV2.this);
						 } catch (IllegalAccessException e) {
							 e.printStackTrace();
						 }
						 LogUtil.i("DATA", "完成显示" + Utils.getNowTime());
						 loadLyt.setVisibility(View.GONE);
						 emptyLyt.setVisibility(View.GONE);
						 reloadLyt.setVisibility(View.GONE);
						 contentLyt.setVisibility(View.VISIBLE);
						 break;
					 case 0:
						 loadLyt.setVisibility(View.GONE);
						 emptyLyt.setVisibility(View.GONE);
						 reloadLyt.setVisibility(View.GONE);
						 contentLyt.setVisibility(View.GONE);
						 break;
				 }
			 }
		 };

		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					if (!threeLevelDataList.isEmpty())
						threeLevelDataList.clear();
					/**
					 * 加载大系列
					 */
					if (!serieEntities.isEmpty()) {
						LogUtil.i("DATA","开始加载大系列2"+Utils.getNowTime());
						for (int i = 0; i < serieEntities.size(); i++) {
							SeriesForNodeEntity seriesForNodeEntity = new SeriesForNodeEntity(serieEntities.get(i).id, "0", serieEntities.get(i).name,
									"",bookListEntityFromNet.childSeriesBooksList.get(i).childSeriesCount);
							seriesForNodeEntity.setSerieEntity(serieEntities.get(i));
							threeLevelDataList.add(seriesForNodeEntity);
						}
						LogUtil.i("DATA","完成加载大系列2"+Utils.getNowTime());
					}
					/**
					 * 加载子系列
					 */
					LogUtil.i("DATA","开始加载子系列"+Utils.getNowTime());
					for (int i = 0; i < bookListEntityFromNet.childSeriesBooksList.size(); i++) {
						SeriesForNodeEntity seriesForNodeEntity = new SeriesForNodeEntity(bookListEntityFromNet.childSeriesBooksList.get(i).childSeriesId,
								bookListEntityFromNet.childSeriesBooksList.get(i).seriesId, bookListEntityFromNet.childSeriesBooksList.get(i).childSeriesName,
								"", bookListEntityFromNet.childSeriesBooksList.get(i).childSeriesBookIdList.size());
						seriesForNodeEntity.setChildSerieEntity(bookListEntityFromNet.childSeriesBooksList.get(i));
						threeLevelDataList.add(seriesForNodeEntity);
					}
					LogUtil.i("DATA","完成加载子系列"+Utils.getNowTime());

					for (int i = 0;i< bookListEntityFromNet.dataList.size();i++){
						if (bookEntity.id.equals(bookListEntityFromNet.dataList.get(i))){
							bookListEntityFromNet.dataList.get(i).bCanUpdate = bookEntity.bCanUpdate;
							bookListEntityFromNet.dataList.get(i).bookZipState = bookEntity.bookZipState;
						}
					}
					message.what = 1;
					message.obj = threeLevelDataList;

				} catch (Exception e) {
					message.what = 0;
					e.printStackTrace();
				}
				myHandler.sendMessage(message);
			}
		}.start();
	}


	/**
	 * 20160405--
	 * 390694--添加版本判断
	 * 刷新按钮在AllBooksWithDbAllSeriesListAdapterV5
	 * @param type
	 */
	public void refreshDataLst(int type, boolean isRefresh) {// 刷新
		String shareDate = EntryCataStoreUtil.get(this);
		final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		final String nowDate = dateFormat.format(new Date());
		if (!shareDate.equals(nowDate)) {// 当日首次刷新增加积分
			EntryCataStoreUtil.save(this, nowDate);
			Utils.submitPoints(this, 1, "", false);
		}
		//20160608--390694改
		getAllBooksWithDbAllSeries(type,isRefresh);
	}

	/**
	 * 390694
	 *屏蔽原有的资料更新方式
	 * 2016-11-30
	 * @param bTopRefresh
	 * @param type
	 */
	/*private void getAllBooksWithDbAllSeries(boolean bTopRefresh, int type) {

		View convertView = findViewById(R.id.lyt_parent);
		ExpandableListView listView = (ExpandableListView) convertView
				.findViewById(R.id.lst_default_list);
		AllBooksWithDbAllSeriesListHandlerV3 handler = new AllBooksWithDbAllSeriesListHandlerV3(
				this, convertView, type, bTopRefresh);
		if (type == 0) {
			mAdapter = new AllBooksWithDbAllSeriesListAdapterV5(listView, this,
					convertView, R.layout.layout_loading,
					R.layout.layout_reloading, handler, type);
		} else {
			mAdapterDownLoad = new AllBooksWithDbAllSeriesListAdapterV5(
					listView, this, convertView, R.layout.layout_loading,
					R.layout.layout_reloading, handler, type);

		}
	}*/

	/**
	 * 390694
	 * 优化资料更新方式
	 * 2016-11-30
	 * @param type   更新类型：0-全部；1-已下载
	 *
	 */
	private void getAllBooksWithDbAllSeries(int type, final boolean isRefresh) {
		final View convertView = findViewById(R.id.lyt_parent);
		download_listView = (LinearLayout) convertView.findViewById(R.id.lst_three_level_parent);
		downloaded_ListView = (LinearLayout) convertView.findViewById(R.id.lst_expandable_list_parent);
		if (type == 0) {
			if (download_listView.getVisibility() == View.GONE){
				download_listView.setVisibility(View.VISIBLE);
			}
			if (downloaded_ListView.getVisibility() == View.VISIBLE){
				downloaded_ListView.setVisibility(View.GONE);
			}
			//重新加载时，显示进度条
			//loadLyt.setVisibility(View.VISIBLE);
			//异步线程加载数据
			new getAllBooksTask(this, isRefresh).execute();
		} else {
			if (download_listView.getVisibility() == View.VISIBLE){
				download_listView.setVisibility(View.GONE);
			}
			if (downloaded_ListView.getVisibility() == View.GONE){
				downloaded_ListView.setVisibility(View.VISIBLE);
			}
			ExpandableListView listView = (ExpandableListView) convertView
					.findViewById(R.id.lst_default_list);
			AllBooksWithDbAllSeriesListHandlerV3 handler = new AllBooksWithDbAllSeriesListHandlerV3(
					this, convertView, type, false);
			mAdapterDownLoad = new AllBooksWithDbAllSeriesListAdapterV5(
					listView, this, convertView, R.layout.layout_loading,
					R.layout.layout_reloading, handler, type);
		}
	}

	private void findView(){
		final View convertView = findViewById(R.id.lyt_parent);
		loadLyt = (LinearLayout) convertView.findViewById(R.id.lyt_three_level_load);
		emptyLyt = (LinearLayout) convertView.findViewById(R.id.lyt_three_level_empty);
		reloadLyt = (LinearLayout) convertView.findViewById(R.id.lyt_three_level_reload);
		contentLyt = (ListView) convertView.findViewById(R.id.lst_three_level_list);

		reloadBtn = (Button) convertView.findViewById(R.id.btn_three_level_reload);
		reloadBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				loadLyt.setVisibility(View.VISIBLE);
				reloadLyt.setVisibility(View.GONE);
				new getAllBooksTask(DownloadManagerActivityV2.this,false).execute();
			}
		});
		loadTv = (TextView) convertView.findViewById(R.id.tv_default_list_load);
		cbDownloadList = (CheckBox) findViewById(R.id.cb_download_list);
		cbHasDownlaod = (CheckBox) findViewById(R.id.cb_has_download);
	}

	private void initWindow() {
		if(!DownloadBookLstInitFinishUtil.getDownloadBookFinished(mActivity)){
			loadLyt.setVisibility(View.GONE);
			dialog = new GroupDialog(this);
			dialog.builder(R.style.AlertDialogStyle).
					setAlertDialogSize(0.05).setProgressBarRound(100).setCancleBack(mActivity).
					setCancleOnTouchOutside(false).show();
			HctApplication.percent = 5;
		}

		if (fromMain) {
			LogUtil.i("DATA","从主界面进来执行刷新");
			refreshDataLst(0,false);
		} else {
			initDataLst(0,false);
		}
		if (!DownloadBookLstInitFinishUtil.getDownloadBookFinished(this)
				/*&& !isServiceWork(mActivity, SERVICE_NAME)*/) {
			LogUtil.i("DATA","启动TechnicalDataUpdateService服务");
			Intent intent = new Intent(this, TechnicalDataUpdateService.class);
			intent.putExtra("isFirstInstall",true);
			this.startService(intent);
		}
	}

	/**
	 *检查服务是否在后台运行
	 */
	public boolean isServiceWork(Context mContext, String serviceName){
		boolean isWork = false;
		ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> runningServiceInfos = myAM.getRunningServices(40);
		if (runningServiceInfos.size() <= 0){
			return false;
		}
		for (int i = 0;i<runningServiceInfos.size();i++){
			String mName = runningServiceInfos.get(i).service.getClassName().toString();

			if (mName.equals(serviceName)){
				isWork = true;
				break;
			}
		}
		return isWork;
	}
	public class DownloadUpdateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String downloadUrl = intent
					.getStringExtra(HctConstants.ON_DOWNLOAD_SERIVE_KEY_DOWNLOAD_URL);
			BookListEntity.BookEntity bookEntity = (BookListEntity.BookEntity) intent
					.getSerializableExtra(HctConstants.ON_ACTIVITY_KEY_BOOK_ENTITY);
			boolean bSwitchDownloadState = intent.getBooleanExtra(
					HctConstants.ON_DOWNLOAD_SERIVE_KEY_SWITCH_DOWNLOAD_STATE,
					false);

			if (bSwitchDownloadState) {
				LogUtil.i("DATA","接收到广播,去更新状态");
				downloadManagerAdapter.updateBooksLayout(downloadUrl,bookEntity);

				return;
			}
			if (!bSwitchDownloadState
					&& ((System.currentTimeMillis() - mLExitTime) > mLDelayTime)) {
				mLExitTime = System.currentTimeMillis();
				downloadManagerAdapter.updateBooksLayout(downloadUrl,bookEntity);
			}
		}
	}

	@Override
	public void onBackPressed() {
		if (fromMain) {
			startActivity(new Intent(DownloadManagerActivityV2.this,
					MainActivityV2.class));
			finish();
		} else {
			finish();
		}
		super.onBackPressed();
	}

	/**
	 * 异步任务。获取服务器数据
	 */
	public class getAllBooksTask extends AsyncTask<Activity, Integer, List<SeriesForNodeEntity>>
	{
		HctBackTestJsonController backTestJsonController;
		private Activity activity;
		private boolean isRefresh;
		List<BookListEntity.BookEntity> bookDataList = new ArrayList<BookListEntity.BookEntity>();
		public getAllBooksTask(Activity activity, boolean isRefresh){
			this.activity = activity;
			this.isRefresh = isRefresh;
			backTestJsonController = new HctBackTestJsonController(
					activity);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			LogUtil.i("DATA","onPreExecute");
			/*不能放在onPreExecute（）里操作，会堵塞线程
			loadLyt.setVisibility(View.VISIBLE);
			emptyLyt.setVisibility(View.GONE);
			reloadLyt.setVisibility(View.GONE);
			contentLyt.setVisibility(View.GONE);*/
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			loadLyt.setVisibility(View.GONE);
		}

		@Override
		protected List<SeriesForNodeEntity> doInBackground(Activity... activities) {
			try {
				if (!threeLevelDataList.isEmpty())
					threeLevelDataList.clear();

				//从数据库获取大系列
				serieEntities = mController.selectSerieListFromDb();
				HctResult bookResult = new HctResult();

				//LogUtil.i("DATA","从服务器或数据库获取资料"+Utils.getNowTime());
				bookResult = mController.getAllBooksFromNetOrDb(backTestJsonController);
				//LogUtil.i("DATA","完成从服务器或数据库获取资料"+Utils.getNowTime());

				if (bookResult.status == HctConstants.STATUS_SUCCESS) {
					mMaxItems = bookResult.totalSize;
					BookListEntity result  = (BookListEntity) bookResult.data;
					bookListEntityFromNet = result;

					if (isRefresh){
						LogUtil.i("DATA","点击刷新按钮时启动更新的服务");
						Intent intent = new Intent(DownloadManagerActivityV2.this,TechnicalDataUpdateService.class);
						intent.putExtra("isFirstInstall",false);
						DownloadManagerActivityV2.this.startService(intent);
					}

					/**
					 * 加载大系列
					 */
					if (!serieEntities.isEmpty()) {
						//LogUtil.i("DATA","开始加载大系列2"+Utils.getNowTime());
						for (int i = 0; i < serieEntities.size(); i++) {
							SeriesForNodeEntity seriesForNodeEntity = new SeriesForNodeEntity(serieEntities.get(i).id, "0", serieEntities.get(i).name,
									"",result.childSeriesBooksList.get(i).childSeriesCount);
							seriesForNodeEntity.setSerieEntity(serieEntities.get(i));
							threeLevelDataList.add(seriesForNodeEntity);
						}
						//LogUtil.i("DATA","完成加载大系列2"+Utils.getNowTime());
					}
					/**
					 * 加载子系列
					 */
					//LogUtil.i("DATA","开始加载子系列"+Utils.getNowTime());
					for (int i = 0; i < result.childSeriesBooksList.size(); i++) {
						SeriesForNodeEntity seriesForNodeEntity = new SeriesForNodeEntity(result.childSeriesBooksList.get(i).childSeriesId,
								result.childSeriesBooksList.get(i).seriesId, result.childSeriesBooksList.get(i).childSeriesName,
								"", result.childSeriesBooksList.get(i).childSeriesBookIdList.size());
						seriesForNodeEntity.setChildSerieEntity(result.childSeriesBooksList.get(i));
						threeLevelDataList.add(seriesForNodeEntity);
					}
					//LogUtil.i("DATA","完成加载子系列"+Utils.getNowTime());
					return threeLevelDataList;
				} else {
					return null;

				}
			} catch (Exception ex) {
				ex.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(final List<SeriesForNodeEntity> bookListEntity) {
			super.onPostExecute(bookListEntity);
			if (bookListEntity == null || bookListEntity.isEmpty()){
				LogUtil.i("DATA","onPostExecute");
				loadLyt.setVisibility(View.GONE);
				emptyLyt.setVisibility(View.GONE);
				reloadLyt.setVisibility(View.VISIBLE);
				contentLyt.setVisibility(View.GONE);
			}else{
				LogUtil.i("DATA", "显示" + Utils.getNowTime());
				//390778 当界面显示出书，设置进度
				HctApplication.percent=10;
				try {
					boolean state = DownloadBookLstInitFinishUtil.getDownloadBookFinished(getApplication());
					downloadManagerAdapter = new DownloadManagerAdapter<SeriesForNodeEntity>(contentLyt,
							activity, bookListEntity, 1, 0,state);
					contentLyt.setAdapter(downloadManagerAdapter);
					downloadManagerAdapter.setOnTreeNodeClickListener(DownloadManagerActivityV2.this);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				LogUtil.i("DATA", "完成显示" + Utils.getNowTime());
				loadLyt.setVisibility(View.GONE);
				emptyLyt.setVisibility(View.GONE);
				reloadLyt.setVisibility(View.GONE);
				contentLyt.setVisibility(View.VISIBLE);

			}
		}
	}

	/**
	 * 根据子系列ID找到子系列下所有书籍，
	 * @param bookListEntity
	 * @return
	 */
	public List<BookListEntity.BookEntity> getBookInfoFromChildSeriesBooks(BookListEntity bookListEntity,SerieListEntity.ChildSerieEntity childSerieEntity){
		List<BookListEntity.BookEntity> bookDataList = new ArrayList<BookListEntity.BookEntity>();
		if (bookListEntity == null || childSerieEntity == null)
			return null;

		List<String> bookIdList = new ArrayList<String>();

		for (int childSeriesBookId = 0; childSeriesBookId < childSerieEntity.childSeriesBookIdList.size(); childSeriesBookId++) {
			bookIdList.add(childSerieEntity.childSeriesBookIdList.get(childSeriesBookId));
		}

		BookListEntity.BookEntity book;
		for (int bookIndex = 0; bookIndex< bookListEntity.dataList.size(); bookIndex++) {
			for (int index = 0; index < bookIdList.size();index++){
				if (bookIdList.get(index).equals(bookListEntity.dataList.get(bookIndex).id)){
					book = new BookListEntity.BookEntity();
					book.childSeriesId = childSerieEntity.childSeriesId;
					book.seriesId = childSerieEntity.seriesId;
					book.childSeriesName = childSerieEntity.childSeriesName;

					book._id = bookListEntity.dataList.get(bookIndex)._id;
					book.id = bookListEntity.dataList.get(bookIndex).id;
					book.bookName = bookListEntity.dataList.get(bookIndex).bookName;
					book.booktypeId = bookListEntity.dataList.get(bookIndex).booktypeId;
					book.booktypeName = bookListEntity.dataList.get(bookIndex).booktypeName;
					book.bookFileSize = bookListEntity.dataList.get(bookIndex).bookFileSize;
					book.versionCode = bookListEntity.dataList.get(bookIndex).versionCode;
					book.download_url = bookListEntity.dataList.get(bookIndex).download_url;
					book.bookZipState = bookListEntity.dataList.get(bookIndex).bookZipState;
					book.progress = bookListEntity.dataList.get(bookIndex).progress;
					book.bCanUpdate = bookListEntity.dataList.get(bookIndex).bCanUpdate;

					book.columnId = bookListEntity.dataList.get(bookIndex).columnId;
					book.displayName = bookListEntity.dataList.get(bookIndex).displayName;
					book.bookFileLongSize = bookListEntity.dataList.get(bookIndex).bookFileLongSize;
					book.currentBookFileLongSize = bookListEntity.dataList.get(bookIndex).currentBookFileLongSize;
					book.currentBookId = bookListEntity.dataList.get(bookIndex).currentBookId;
					book.doWhatClick = bookListEntity.dataList.get(bookIndex).doWhatClick;

					book.suffix = bookListEntity.dataList.get(bookIndex).suffix;

					bookDataList.add(book);

					LogUtil.i("DATA",bookListEntity.dataList.get(bookIndex).bookName);
					LogUtil.i("DATA",bookListEntity.dataList.get(bookIndex).suffix);
					break;
				}
			}
		}
		return bookDataList;
	}


	/**
	 * 三级列表的点击事件
	 * @param node
	 * @param position
	 */
	@Override
	public void onClick(Node node, int position) {
		if (node.getLevel() == 2) {
			//当前书本已下载，点击打开阅读
			final BookListEntity.BookEntity entity = downloadManagerAdapter.getDbBookEntity(node);
			if (entity != null) {
				EntryCatalogUtil catalogUtil = new EntryCatalogUtil();
				try {
					boolean isDownload = catalogUtil.startEntryCatalogActivity(this,
							entity, false);
					if (!isDownload) {
						// 没下载不知道该干嘛，提示？
						downloadManagerAdapter.notifyDataSetChanged();// 说明文件可能不存在，需重新下载
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return;
		}
		if (!node.isRoot()){

			if (node.getChildren().isEmpty()){
				List<SeriesForNodeEntity> childrenBookList = new ArrayList<SeriesForNodeEntity>();
				List<BookListEntity.BookEntity> bookEntityList = new ArrayList<BookListEntity.BookEntity>();
				bookEntityList = getBookInfoFromChildSeriesBooks(bookListEntityFromNet, node.getChildSerieEntity());
				downloadManagerAdapter.clickAddChildSeriesBook(bookEntityList, position);
			}else{
				if (node.isExpand()){
					node.setExpand(false);
				}else{
					node.setExpand(true);
				}
				downloadManagerAdapter.expandOrCollapse(position);
			}

		}else{
			/*if (node.getChildren().size() > 0 && node.isExpand())
			{
				node.setIcon(R.drawable.ic_on);
				//node.setExpand(false);
			} else if (node.getChildren().size() > 0 && !node.isExpand())
			{
				node.setIcon(R.drawable.ic_off);
				//node.setExpand(true);
			}
			downloadManagerAdapter.expandOrCollapse(position);*/

		}
	}
}
